package client.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

import socket.utils;
import Globle.Global;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.FloatMath;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class ShowScreen extends Activity {

	boolean bfirstin = true;
	Socket socket;
	byte[] bmp = null;
	Bitmap bm;
	ImageView img = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.getscreen);

		img = (ImageView) findViewById(R.id.img);
		img.setOnTouchListener(new MuiltPointTouchListener());
	}

	public void caponClick(View v) {
		if (bfirstin) {
			Button btn = (Button) findViewById(R.id.cutscreenbtn);
			btn.setText(getString(R.string.tscreenonmore));
		}
		int len = 0;
		byte[] sendmsg = new byte[1024];

		int index = 0;
		sendmsg[0] = Global.REQUESTSCREN;

		byte[] str = utils.client.sendMsg(new String(sendmsg));

		if (str == null)
			return;
		if (Global.RECVSCRRN == Global.getMsgId(str)) {
			len = str[524] & 0xff;
			len = len | ((str[525] << 8) & 0x0000ff00);
			len = len | ((str[526] << 16) & 0x00ff0000);
			len = len | ((str[527] << 24) & 0xff000000);

			System.out.println("file length = " + len);
			bmp = new byte[len];

			while (len > 0) {
				System.out.println("aaaa");
				byte[] buf = utils.client.recvMsg(len);
				int currlen = buf.length;
				len = len - currlen;
				System.arraycopy(buf, 0, bmp, index, buf.length);
				index += buf.length;
				System.out.println("curr len =" + currlen + "len = " + len);
			}

		}
		System.out.println("hello");
		bm = BitmapFactory.decodeByteArray(bmp, 0, bmp.length);

		img.setImageBitmap(bm);
	}

	public void savescreenClick(View v) throws FileNotFoundException {

		if(bm == null)
			return ;	
	
		String strpatch = getApplicationContext().getFilesDir()
				.getAbsolutePath();
		Date date = new Date();
		String str = null;
		SimpleDateFormat df = new SimpleDateFormat("yyyy_MM_dd_HHmmss");
		strpatch = strpatch + "/imgsave";
		str = df.format(date);
		File file = new File(strpatch);
		if (!file.exists()) {
			file.mkdir();
		}

		File fileimg = new File(strpatch, str + ".png");
		try {
			fileimg.createNewFile();
			FileOutputStream fos = new FileOutputStream(fileimg);
		
			bm.compress(CompressFormat.PNG, 0, fos);
			fos.flush();
			fos.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

		Toast.makeText(this, strpatch+str+".png", Toast.LENGTH_SHORT).show();
	}

	public class MuiltPointTouchListener implements OnTouchListener {
		Matrix matrix = new Matrix();
		Matrix savedMatrix = new Matrix();
		static final int NONE = 0;
		static final int DRAG = 1;
		static final int ZOOM = 2;
		int mode = NONE;
		PointF start = new PointF();
		PointF mid = new PointF();
		float oldDist = 1f;

		public boolean onTouch(View v, MotionEvent event) {
			ImageView view = (ImageView) v;
			switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				matrix.set(view.getImageMatrix());
				savedMatrix.set(matrix);
				start.set(event.getX(), event.getY());
				mode = DRAG;

				break;
			case MotionEvent.ACTION_POINTER_DOWN:
				oldDist = spacing(event);
				if (oldDist > 10f) {
					savedMatrix.set(matrix);
					midPoint(mid, event);
					mode = ZOOM;
				}
				break;
			case MotionEvent.ACTION_UP:
			case MotionEvent.ACTION_POINTER_UP:
				mode = NONE;
				break;
			case MotionEvent.ACTION_MOVE:
				if (mode == DRAG) {
					matrix.set(savedMatrix);
					matrix.postTranslate(event.getX() - start.x, event.getY()
							- start.y);
				} else if (mode == ZOOM) {
					float newDist = spacing(event);
					if (newDist > 10f) {
						matrix.set(savedMatrix);
						float scale = newDist / oldDist;
						matrix.postScale(scale, scale, mid.x, mid.y);
					}
				}
				break;
			}
			view.setImageMatrix(matrix);
			return true;
		}

		private float spacing(MotionEvent event) {
			float x = event.getX(0) - event.getX(1);
			float y = event.getY(0) - event.getY(1);
			return FloatMath.sqrt(x * x + y * y);
		}

		private void midPoint(PointF point, MotionEvent event) {
			float x = event.getX(0) + event.getX(1);
			float y = event.getY(0) + event.getY(1);
			point.set(x / 2, y / 2);
		}
	}

	private class SyncData extends AsyncTask<String, String, String> {

		@Override
		// 将在onPreExecute 方法执行后马上执行，该方法运行在后台线程中
		protected String doInBackground(String... arg0) {

			return "0";
		}

		@Override
		// 在doInBackground 执行完成后，onPostExecute 方法将被UI thread调用
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
		}

		@Override
		// 该方法将在执行实际的后台操作前被UI thread调用
		protected void onPreExecute() {
			super.onPreExecute();
			showdialog(1, "發送中");
		}

		// 用于UI線程更新操作 發送publishProgress(Progress...)后會執行
		// protected void onProgressUpdate(){
		// super.onProgressUpdate();
		// }
	}

	private Dialog dialog;

	private void showdialog(int id, String msg) {
		if (dialog != null)
			dialog.cancel();

		// 對話框
		if (id == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(msg)
					.setCancelable(false)
					.setPositiveButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									;
								}
							});

			dialog = builder.create();
			dialog.show();
		} else if (id == 1)// 等待
		{
			dialog = ProgressDialog.show(ShowScreen.this, "", msg, true);
		}
	}

}